package com.santi.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.santi.entity.Result;
import com.santi.entity.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.santi.entity.User;
import com.santi.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController  //返回json值
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@PostMapping("/login")
	public Map<String, Object> login(String username, String password) throws Exception {
		System.out.println("这是login方法");

		Map<String, Object> result = new HashMap<String, Object>();

		User user = userService.login(username, password);
		System.out.println(user);
		if (user != null) {
			//登录成功
			result.put("code", 200);
			result.put("msg", "登录成功");
		} else {
			//登录失败
			result.put("code", 300);
			result.put("msg", "账号错误");
		}
		//写入前端
		return result;
	}

	@RequestMapping("/register")
	public void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		User user = new User(username, password);
		int result = userService.register(user);
		if (result > 0) {
			//注册成功
			resp.sendRedirect("login.jsp");
		} else {
			//注册失败重新注册
			resp.sendRedirect("register.jsp");


		}

	}

}






